﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ninject;
using Mabalacat.CPS.BusinessLogic.Services.Interfaces;
using Mabalacat.CPS.DataAccess.DataObjects;
using Web.Codes;

namespace Web.admin
{
    public partial class Users : BasePage //System.Web.UI.Page
    {
        [Inject]
        public IUserService _userService { get; set; }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)            
                BindGrid();            
        }

        protected void repeaterTable_ItemCommand(object source, RepeaterCommandEventArgs e) 
        {
            int intTemp = 0;
            switch (e.CommandName.ToLower())
            {
                case Constants.Delete_Command:
                    if (int.TryParse((string)e.CommandArgument, out intTemp))
                        Delete(intTemp);
                    break;
            }
        }
        protected void repeaterTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var user = (User)e.Item.DataItem;
                ((Literal)e.Item.FindControl("DateDateLiteral")).Text = Utils.DateTimeHelper.FormatDateString(user.DateAdded);
                if (user.DateModified.HasValue)
                {                    
                    ((Literal)e.Item.FindControl("ModifiedDateLiteral")).Text = Utils.DateTimeHelper.FormatDateString(user.DateModified.Value);
                }                    
                

            }
        }
        
        #region Implementations
        void BindGrid()
        {
            repeaterTable.DataSource = _userService.GetAll().ToList();
            repeaterTable.DataBind();               
        }
        void Delete(int id)
        {
            _userService.Delete(id);
            if (_userService.Save())
                BindGrid();
        }
        protected string FormatDateString(RepeaterItem item)
        {
            var date = ((User)item.DataItem).DateAdded;            
            return Utils.DateTimeHelper.FormatDateString(date);
        }
        #endregion

    }
}